<template>

    <div class="georeference-container">

        <div class="georeference">

            <div class="title">

                <span>请选择以下任意一种方式进行空间化</span>

                <div class="close-icon" @click="closePanel">
                    <i class="iconfont icon-close"></i>
                </div>

            </div>

            <div class="tab-header">
                <div class="tab-item" :class="{'active':currentTab==='byAddr'}" @click="switchTab('byAddr', 0)">地址</div>
                <div class="tab-item" :class="{'active':currentTab==='byCoord'}" @click="switchTab('byCoord', 1)">经纬度</div>
                <div class="tab-item" :class="{'active':currentTab==='byAdmin'}" @click="switchTab('byAdmin', 2)">行政区</div>
                <div class="tab-active-bar" :style="activeBar"></div>
            </div>

            <div class="tab-body">

                <div class="address body" v-show="currentTab==='byAddr'">
                    <div>
                        <div class="label-select">地址字段</div>
                        <g-select :options="addrFields" v-on:option-select="setAddrField"></g-select>
                    </div>
                    <div>
                        <div class="label-select">上级行政区</div>
                        <g-select :options="addrFields" :hasNull="true" v-on:option-select="setAddrParentField"></g-select>
                    </div>
                </div>

                <div class="lat-lon body"  v-show="currentTab==='byCoord'">
                    <div>
                        <div class="label-select">经度字段</div>
                        <g-select :options="xFields" v-on:option-select="setLon"></g-select>
                    </div>
                    <div>
                        <div class="label-select">纬度字段</div>
                        <g-select :options="yFields" v-on:option-select="setLat"></g-select>
                    </div>
                    <div>
                        <div class="label-select">数据来源</div>
                        <g-select :options="dataSource" v-on:option-select="setSource"></g-select>
                    </div>
                </div>

                <div class="region body" v-show="currentTab==='byAdmin'" >
                    <div>
                        <div class="label-select">行政区字段</div>
                        <g-select :options="addrFields" v-on:option-select="setAdminField"></g-select>
                    </div>
                    <div>
                        <div class="label-select">上级行政区</div>
                        <g-select :options="addrFields" :hasNull="true" v-on:option-select="setAdminParentField"></g-select>
                    </div>
                    <div>
                        <div class="label-select">行政区形状</div>
                        <g-select :options="adminShapeOptions" v-on:option-select="setAdminShape"></g-select>
                    </div>
                </div>
            </div>

            <div class="option-container">
                <div class="start" v-show="!onGeoreference">
                    <g-button round type="primary" @click="startGeoreference" >开始空间化</g-button>
                </div>
                <div class="progress-container" v-show="onGeoreference">
                    <div class="progress-text">{{georeferenceProgress}}%</div>
                    <div class="progress-bar" :style="{width:georeferenceProgress + '%'}"></div>
                </div>
            </div>

        </div>

    </div>

</template>

<script>

    import axios from 'axios'
    import Bus from '../../utils/event_bus'
    import GSelect from '../common/g-select'
    import GButton from '@/components/common/g-button'


    var qs = require('qs');

    export default {

        name: 'georeference',

        data: function() {
            return {
                currentTab: 'byAddr',
                activeBar: {
                    transform: 'translateX(0px)'
                },
                addrFields: [],
                xFields: [],
                yFields: [],
                dataSource: [
                    {value: 1, label: '高德等互联网地图'},
                    {value: 2, label: '百度地图'},
                    {value: 0, label: 'GPS设备'}
                ],
                adminShapeOptions: [
                    {value:'point', label: '点'},
                    {value: 'polygon', label: '面'}
                ],
                onGeoreference: false,
                jobId:'',
                georeferenceProgress: 0,

                addrField: '',
                addrParentField: '',

                lon: '',
                lat: '',
                source: '',

                adminField: '',
                adminParentField: '',
                adminShape: ''

            }
        },

        props: {
            uid: String,
            isPublic: {
                type: Boolean,
                default: false
            }
        },

        components: {
            GSelect,
            GButton
        },

        mounted: function() {

            if (!this.uid) {
                return;
            }

            this.getGeoreferenceField();
        },

        watch: {
            uid() {
                this.getGeoreferenceField();
            }
        },

        methods: {

            close() {
                this.$emit('close');
            },

            switchTab(tab, index) {

                if (this.onGeoreference) {
                    return;
                }

                this.currentTab = tab;
                this.activeBar.transform = `translateX(${index*100}%)`;
            },

            setRefreshStatus(status) {
                this.$emit('refresh-data-list', status);
            },

            getGeoreferenceField() {

                axios.get(`/s/${this.isPublic ? 'public_data' : 'data'}/georeference/${this.uid}/status`)
                    .then((res) => {

                        if (res.data.code === 1) {
                            return;
                        }

                        if (res.data.code !== 0) {
                            this.$message.error(res.data.msg)
                            return;
                        }

                        if (res.data.status === 101) {
                            let data = res.data.data;

                            this.addrFields = data.addrFields.map(this.arrayToOptions);
                            this.xFields = data.xFields.map(this.arrayToOptions);
                            this.yFields = data.yFields.map(this.arrayToOptions);
                        }

                        if (res.data.status === 100) {
                            this.$message.warning('空间化任务正在进行中');
                        }

                    })
                    .catch((err) => {
                        this.$message.error('无法获取空间字段');
                    })
            },

            arrayToOptions(value) {
                return {value: value, label: value};
            },

            startGeoreference() {

                let params = {};
                let currentTab = this.currentTab;

                params.convert_by = currentTab;

                if (currentTab === 'byAddr') {
                    params.addr_field = this.addrField;
                    params.admin_field = this.addrParentField;
                } else if(currentTab === 'byCoord') {
                    params.x_field = this.lon;
                    params.y_field = this.lat;
                    params.offset = this.source;
                } else if(currentTab === 'byAdmin') {
                    params.admin_field = this.adminField;
                    params.parent_field = this.adminParentField;
                    params.admin_shape = this.adminShape;
                }

                if (currentTab === 'byAddr' && !params.addr_field) {

                    this.$message.error('缺少必要的空间化字段');
                    return;

                }

                if (currentTab === 'byAdmin' && !params.admin_field) {

                    this.$message.error('缺少必要的空间化字段');
                    return;

                }

                this.onGeoreference = true;

                axios.post(`/s/${this.isPublic ? 'public_data' : 'data'}/georeference/${this.uid}`, qs.stringify(params))
                    .then((res) => {
                        if (res.data.code != 0) {

                            this.$message.error(res.data.msg);
                            this.onGeoreference = false;

                            return;
                        }

                        let jobId = res.data.data;

                        this.jobId = jobId;

                        this.getGeoreferenceStatus();

                    })
                    .catch((err) => {
                        this.$message.error('空间化任务失败');
                        this.onGeoreference = false;
                    })
            },

            getGeoreferenceStatus() {

                axios.get(`/s/${this.isPublic ? 'public_data' : 'data'}/georeference/${this.uid}/checkJob/${this.jobId}`)
                    .then((res) => {
                        if (res.data.code != 0) {
                            this.$message.error(res.data.msg);
                            this.onGeoreference = false;
                            return;
                        }

                        let data = res.data.data;

                        if (!data.done) {
                            this.georeferenceProgress = data.jobPercent;

                            setTimeout(() => {
                                this.getGeoreferenceStatus();
                            },5000)

                        } else {
                            this.georeferenceProgress = 100;
                            setTimeout(() => {

                                this.onGeoreference = false;
                                this.setRefreshStatus(true);
                                Bus.$emit('georeference-success', this.uid);        // 通知map-view组件
                                Bus.$emit('georeference-success-mydata', this.uid); // 通知my-data组件
                                this.close();

                            },1000)
                        }

                    })
                    .catch((res) => {
                        this.$message.error('数据空间化发生错误');
                        this.onGeoreference = false;
                    })

            },

            setAddrField(value) {
                this.addrField = value;
            },

            setAddrParentField(value) {
                this.addrParentField = value;
            },

            setLat(value) {
                this.lat = value;
            },

            setLon(value) {
                this.lon = value;
            },

            setSource(value) {
                this.source = value;
            },

            setAdminField(value) {
                this.adminField = value;
            },

            setAdminParentField(value) {
                this.adminParentField = value;
            },

            setAdminShape(value) {
                this.adminShape = value;
            },

            closePanel() {
                Bus.$emit('georeference-cancel');
            }
        },
    }
</script>

<style lang="scss" rel="stylesheet/scss">

    @import "common";
    $uploadBackground: #F4F8FB;
    $bgProgress: #dce7f4;

    .georeference-container {

        position: absolute;
        @include absolute (0px, 0px, 0px, 0px);
        background: rgba(0, 0, 0, .5);
        z-index: 20;

        .toggle-select {
            border: 1px solid #e6e9f0 !important;
        }

        .georeference {

            width: 100%;
            height: 100%;
            max-width: 700px;
            max-height: 400px;

            position: absolute;
            margin: auto;
            top: 0; left: 0; right: 0; bottom: 0;
            overflow: auto;

            background-color: white;

            border-radius: 3px;

            .title {

                height: 48px;
                line-height: 48px;
                font-size: 14px;
                border-bottom: 1px solid #e6e9f0;
                padding: 0 14px;

                > span {
                    float: left;
                    font-weight: 500;
                }

                .sub-title {
                    font-size: 12px;
                    color: #889;
                    position: absolute;
                    top: 1px;
                    left: 92px;
                }

                .close-icon {

                    float: right;

                    &:hover {
                        cursor: pointer;
                    }

                }
            }

            >div {
                @include box-sizing(border-box);
            }

            .tab-header{

                overflow: hidden;
                position: relative;
                height: 50px;
                border-bottom: 1px solid $bdGray;

                .tab-item{
                    width: 33.33%;
                    overflow: hidden;
                    padding: 16px 0;
                    float: left;
                    text-align: center;
                    cursor: pointer;

                    &:hover{
                        font-weight: bold;
                    }

                    &.active{
                        color: $primary;

                        &:hover{
                            font-weight: 400;
                        }
                    }
                }

                .tab-active-bar{
                    width: 33.33%;
                    position: absolute;
                    bottom: -1px;
                    left: 0;
                    height: 2px;
                    background-color: $lightPrimary;
                    z-index: 20;
                    transition: transform .3s cubic-bezier(.645,.045,.355,1);
                }
            }

            .tab-body{

                height: calc(100% - 50px - 48px);
                position: relative;

                .address{

                    >div{
                        width: 50%;
                    }
                }

                .label-select{
                    margin-bottom: 12px;
                }

                .lat-lon{
                    >div{
                        width: 33.33%;
                    }
                }

                .region{
                    >div{
                        width: 33.33%;
                    }
                }

                .body{
                    padding: 12px;
                    width: 100%;
                    height: 100%;
                    overflow: hidden;

                    >div{
                        float: left;
                        height: 100%;
                        padding: 10px 30px;
                    }
                }
            }

            .option-container{
                height: 48px;
                line-height: 46px;
                width: 100%;
                border-top: 1px solid $bdGray;
                position: absolute;
                bottom: 0;

                .start {

                    text-align: center;

                    >button{
                        padding: 0 24px;
                    }
                }



                .progress-container{
                    width: 100%;
                    height: 100%;
                    background-color: $uploadBackground;
                    position: relative;

                    .progress-text{
                        position: absolute;
                        color: $primary;
                        z-index: 20;
                        width: 40px;
                        left: calc(50% - 20px);
                    }

                    .progress-bar {
                        position: absolute;
                        background-color: $bgProgress;
                        z-index: 19;
                        top: 0;
                        bottom: 0;
                        left: 0;
                        @include transition(all .5s);

                    }
                }
            }
        }

    }

</style>
